//
//  FileUpdateUtil.m
//  UpdateFileApp
//
//  Created by PCQ on 10/02/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "FileUpdateUtil.h"
#import <sys/xattr.h> // JW [15-Oct-2012] fix iOS data storage problem

@implementation FileUpdateUtil

+(NSDate *)dateFromString:(NSString *)date
{
	NSDate *formatedDate;
	@try {  
		NSDateFormatter *df = [[NSDateFormatter alloc] init];  
		df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";  
		df.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];  
		df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];  
		formatedDate= [df dateFromString:date];  
	}  
	@catch (NSException * e) {  
		DebugLog(@"Error parsing last modified date: %@ - %@", date, [e description]);  
	}  
	return formatedDate;
}

+(NSDate *)getModificationDate:(NSString *)path errorDetails:(NSError**)error 
{
	NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:error];  
	if (!error) { 
		NSDate *lastModifiedLocal = [fileAttributes fileModificationDate];  
		DebugLog(@"lastModifiedLocal : %@", lastModifiedLocal);  
		return lastModifiedLocal;
	}
	return nil;
}

+(BOOL)copyFile:(NSString *)sourcePath destination:(NSString *)locationPath overwriteExisting:(BOOL)replaceExisting errorDetails:(NSError**)error 
{
	
	if (![[NSFileManager defaultManager]fileExistsAtPath:locationPath] || replaceExisting)
	{
		
		[[NSFileManager defaultManager] copyItemAtPath:sourcePath toPath:locationPath error:error];
		
		
		if (![[NSFileManager defaultManager]fileExistsAtPath:locationPath])
		{
			return FALSE;
		}
	}
	else
	{
		*error =[NSError errorWithDomain:NSHybridErrorDomain code:NSHybridErrorFileAlreadyExists userInfo:nil];
		return FALSE;
	}
	return TRUE;
}

+(BOOL)deleteFile:(NSString *)path errorDetails:(NSError **)error
{
	[[NSFileManager defaultManager]removeItemAtPath:path error:error];
	if (error)
	{
		return FALSE;
	}
	else {
		return TRUE;
	}
	
}

/*
 * *************************************************************************
 * iOS Data Storage issue by changing data storage folder to cached folder,
 * as to support the scope from iOS system version<=5.0, system version ==5.0.1, other iOS version, 
 * to the data storage folder will be changed 
 * to NSCachesDirectory.
 * *************************************************************************
 */
+(NSString *) getCachedResourceFolderPath:(NSString *)resourceFolderKay
{
    NSString *cachedResourceFolderPath;
    
    if ([[UIDevice currentDevice].systemVersion isEqualToString:@"5.0.1"])
    {
        DebugLog(@"iOS 5.0.1 handling.");
        DebugLog(@"create cached resource folder path in (Library/Application Support).");
        
        // to use cache folder as the base folder.
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        
        // get the cached resources folder with resource folder key.
        cachedResourceFolderPath = [NSString stringWithString:[documentsDirectory stringByAppendingPathComponent:resourceFolderKay]];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        // JW [15-Oct-2012] - Verify if file exist before operation
        if (![fileManager fileExistsAtPath:cachedResourceFolderPath]) 
        {
            if ([fileManager createDirectoryAtPath:cachedResourceFolderPath
                       withIntermediateDirectories:YES 
                                        attributes:nil 
                                             error:nil]==NO)
            {
                DebugLog(@"fileManager createDirectoryAtPath:rootResourceFolder attributes:nil failed.");
            }
            else
            {
                DebugLog(@"fileManager createDirectoryAtPath:rootResourceFolder attributes:nil successful.");
                
                // JW [15-Oct-2012] fix iOS data storage problem
                // set prevent backup flag.
                NSURL *URL = [NSURL fileURLWithPath:cachedResourceFolderPath];
                [self addSkipBackupAttributeToItemAtURL_iOS501:URL];
            }
        }
        else
        {
            DebugLog(@"existing folder, no need to create a new folder");
            
            // JW [15-Oct-2012] fix iOS data storage problem
            // check the flag if existing and set the prevent.
            NSURL *URL = [NSURL fileURLWithPath:cachedResourceFolderPath];
            [self addSkipBackupAttributeToItemAtURL_iOS501:URL];
        }
    }
    else if ([[UIDevice currentDevice].systemVersion floatValue] <= 5.0)
    {
        DebugLog(@"iOS 5.0 and below without 5.0.1 handling."); 
        
        cachedResourceFolderPath = [FileUpdateUtil createCachedResourceFolderPathInLibraryCaches:resourceFolderKay];        
    }
    else 
    {
        DebugLog(@"other iOS version handling.");
        DebugLog(@"create cached resource folder path in (Library/Application Support).");
        
        // to use cache folder as the base folder.
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        
        // get the cached resources folder with resource folder key.
        cachedResourceFolderPath = [NSString stringWithString:[documentsDirectory stringByAppendingPathComponent:resourceFolderKay]];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        // JW [15-Oct-2012] - Verify if file exist before operation
        if (![fileManager fileExistsAtPath:cachedResourceFolderPath])
        {
            if ([fileManager createDirectoryAtPath:cachedResourceFolderPath
                       withIntermediateDirectories:YES 
                                        attributes:nil 
                                             error:nil]==NO)
            {
                DebugLog(@"fileManager createDirectoryAtPath:rootResourceFolder attributes:nil failed.");
            }
            else
            {
                DebugLog(@"fileManager createDirectoryAtPath:rootResourceFolder attributes:nil successful.");
                
                // JW [15-Oct-2012] fix iOS data storage problem
                // set prevent backup flag.
                NSURL *URL = [NSURL fileURLWithPath:cachedResourceFolderPath];
                [self addSkipBackupAttributeToItemAtURL:URL];
            }
        }
        else
        {
            DebugLog(@"existing folder, no need to create a new folder");
            
            // JW [15-Oct-2012] fix iOS data storage problem
            // check the flag if existing and set the prevent.
            NSURL *URL = [NSURL fileURLWithPath:cachedResourceFolderPath];
            [self addSkipBackupAttributeToItemAtURL:URL];
        }
    }
    
    return cachedResourceFolderPath;
}

+(NSString *) createCachedResourceFolderPathInLibraryCaches:(NSString *)resourceFolderKay
{
    DebugLog(@"create cached resource folder path in (Library/Caches).");
    
    NSString *cachedResourceFolderPath;
    
    // to use cache folder as the base folder.
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    // get the cached resources folder with resource folder key.
    cachedResourceFolderPath = [NSString stringWithString:[documentsDirectory stringByAppendingPathComponent:resourceFolderKay]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager isExecutableFileAtPath:cachedResourceFolderPath])
    {
        if ([fileManager createDirectoryAtPath:cachedResourceFolderPath
                   withIntermediateDirectories:YES 
                                    attributes:nil 
                                         error:nil]==NO)
        {
            DebugLog(@"fileManager createDirectoryAtPath:rootResourceFolder attributes:nil failed.");
        }
    }
    
     return cachedResourceFolderPath;
}

// JW [15-Oct-2012] fix iOS data storage problem
+(BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
{
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
    
    NSError *error = nil;
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
    if(!success){
        DebugLog(@"Success setting prevent backup flag - %@", [URL lastPathComponent]);
    } else {
        DebugLog(@"Fail setting prevent backup flag - %@, Error = %@", [URL lastPathComponent], error);
    }
    
    return success;
}

// JW [15-Oct-2012] fix iOS data storage problem
+(BOOL)addSkipBackupAttributeToItemAtURL_iOS501:(NSURL *)URL
{
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
    
    const char* filePath = [[URL path] fileSystemRepresentation];
    
    const char* attrName = "com.apple.MobileBackup";
    u_int8_t attrValue = 1;
    
    int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
    if (result == 0) {
        DebugLog(@"Success setting prevent backup flag - %@", [URL lastPathComponent]);
    } else {
        DebugLog(@"Fail setting prevent backup flag - %@, Return code = %d", [URL lastPathComponent], result);
    }
    
    return result == 0;
}

// background image support
#pragma mark -
#pragma mark - Local Resources File System Util Methods
+(BOOL) setupFolderPath:(NSString *)folerPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager isExecutableFileAtPath:folerPath])
    {
        if ([fileManager createDirectoryAtPath:folerPath
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:nil]==NO)
		{
            //DebugRLRLog(@"fileManager createDirectoryAtPath fail");
            return NO;
		}
    }
    
    return YES;
}

+(BOOL) copyAndReplaceWithNewFile:(NSString *)sourceFilePath
                   targetFilePath:(NSString *)targetFilePath
{
    BOOL flag = YES;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:targetFilePath])
    {
        
        if (![fileManager removeItemAtPath:targetFilePath error:NULL])
        {
            
            return NO;
        }
    }
    
    if (![fileManager copyItemAtPath:sourceFilePath toPath:targetFilePath error:NULL])
    {
        
        return NO;
    }
    
    
    return flag;    
}

@end
